from wtforms import StringField, PasswordField,BooleanField
from wtforms.validators import Length, Email, \
    ValidationError, EqualTo, any_of

from flask_wtf import Form, RecaptchaField

from .base import DataRequired
from app.models.user import User


class EmailForm(Form):
    userid = StringField('电子邮件', validators=[DataRequired(), Length(1, 64),
                                             Email(message='电子邮箱不符合规范')])


class ResetPasswordForm(Form):
    password1 = PasswordField('新密码', validators=[
        DataRequired(), Length(6, 20, message='密码长度至少需要在6到20个字符之间'),
        EqualTo('password2', message='两次输入的密码不相同')])
    password2 = PasswordField('确认新密码', validators=[
        DataRequired(), Length(6, 20)])


class ChangePasswordForm(Form):
    old_password = PasswordField('原有密码', validators=[DataRequired()])
    new_password1 = PasswordField('新密码', validators=[
        DataRequired(), Length(6, 10, message='密码长度至少需要在6到20个字符之间'),
        EqualTo('new_password2', message='两次输入的密码不一致')])
    new_password2 = PasswordField('确认新密码字段', validators=[DataRequired()])


class LoginForm(EmailForm):
    # recaptcha = RecaptchaField()
    pwd = PasswordField('密码', validators=[
        DataRequired(message='密码不可以为空，请输入你的密码')])
    flag = BooleanField('免登陆状态')
    # def validate_userid(self, field):
    #     if not User.query.filter_by(userid=field.data).first():
    #         raise ValidationError('用户名记错了吧')
    def validate(self):
        check_validate = super(LoginForm, self).validate()
        # If validator no pass
        if not check_validate:
            return False
        # Check the user whether exist.
        user = User.query.filter_by(userid=self.userid.data).first()
        if not user:
            self.userid.errors.append('用户名记错了吧')
            return False
        return True


class RegisterForm(EmailForm):
    nickname = StringField('昵称', validators=[
        DataRequired(), Length(2, 10, message='昵称至少需要两个字符，最多10个字符')])

    sex = StringField('性别', validators=[
        DataRequired(), any_of("man,female")])

    tel = StringField('手机号', validators=[
        DataRequired()])

    pwd = PasswordField('密码', validators=[
        DataRequired(), Length(4, 20)])

    def validate_userid(self, field):
        if User.query.filter_by(userid=field.data).first():
            raise ValidationError('电子邮件已被注册')

    # 昵称可以重复
    # def validate_nickname(self, field):
    #     if User.query.filter_by(nickname=field.data).first():
    #         raise ValidationError('昵称已存在')
